//
//  WCRegisterViewController.m
//  WC
//
//  Created by 杨鑫 on 15/4/28.
//  Copyright (c) 2015年 智康. All rights reserved.
//

#import "WCRegisterViewController.h"
#import "NSString+Utilities.h"
//single
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCTimer.h"
#import "Constants.h"
//
#import "Macros.h"
#import "WCBorderView.h"
#import "WCDefaultManager.h"

//#import "ChatManager.h"

static __weak WCTimer *timerFgt;
static __weak WCTimer *timerReg;

@interface WCRegisterViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *invateCodeTF;
@property (weak, nonatomic) IBOutlet UILabel *invateLabel;
@property (weak, nonatomic) IBOutlet WCBorderView *inviteBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inviteBgViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inviteLabelHeight;

@property (weak, nonatomic) IBOutlet UILabel *label3;
@property (weak, nonatomic) IBOutlet UITextField *account;



@property (weak, nonatomic) IBOutlet UITextField *code;
@property (weak, nonatomic) IBOutlet UITextField *password;

@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *save;

@property (nonatomic) WCViewControllerMode mode;
@property (strong, nonatomic) NSString *urlCode;
@property (strong, nonatomic) NSString *url;

@end

@implementation WCRegisterViewController

#pragma mark - Life Circle

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mode = WCViewControllerModeRegister;
       
        
        self.urlCode = @"patient/account/reg/verifyCode/%@";
        self.url = @"patient/account/reg";
       
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    
    
    if (self.mode == WCViewControllerModeForgotPassword ||self.mode == WCViewControllerModeMotifyPassword) {
        if (self.mode == WCViewControllerModeForgotPassword) {
            self.title = @"忘记密码";
            self.label3.text = @"请重置密码";
            [self.save setTitle:@"找回密码" forState:UIControlStateNormal];
        }else{
            self.account.text =[[[WCDefaultManager shareMg] account] mobile];
            self.account.enabled = NO;
            self.title = @"修改密码";
            self.label3.text = @"请重置密码";
            [self.save setTitle:@"修改密码" forState:UIControlStateNormal];

            
        }
       
        self.invateLabel.hidden = YES;
        self.inviteBgView.hidden =YES;
        self.inviteLabelHeight.constant = 0;
        self.inviteBgViewHeight.constant = 0;
        
        self.urlCode = @"nurse/account/resetpwd/verifyCode/%@";
        self.url = @"nurse/account/resetpwd";
        
    }else{
        self.title = @"注册";
//       [self setTitleLabel:@"注册" width:100];
    }
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.mode == WCViewControllerModeRegister) {
        timerReg.securityCode = self.codeBtn;
    } else {
        timerFgt.securityCode = self.codeBtn;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [timerFgt deallocTimer];
    timerFgt ==nil;
}
- (void)successPageback
{
    if (self.mode) {
        if(self.mode ==WCViewControllerModeMotifyPassword){
            [[WCDefaultManager shareMg] updatePwdWithPwd:[self.password.text md5String]];
           

        }
    }
    
    [self pageBack];
}

#pragma mark - NSTimer

- (void)countDown
{
    __block WCTimer *timer = [[WCTimer alloc] init];
    timer.count = 60;
    timer.securityCode = self.codeBtn;
    timer.timeEnd = ^{
        timer = nil;
    };
    [timer start:1];
    
    if (self.mode == WCViewControllerModeRegister) {
        timerReg = timer;
    } else {
        timerFgt = timer;
    }
}

#pragma mark - setter

- (void)setViewController:(WCViewControllerMode)mode
{
    self.mode = mode;
}

#pragma mark - Action

- (IBAction)sendCode:(id)sender {
    NSString *mobile = self.account.text;
    if ([mobile isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"手机号不能为空" withView:self.view];
        return;
    }
  
    
    if ([mobile isMobile]) {
        //关闭按钮
        __weak UIButton *weakBtn = self.codeBtn;
        weakBtn.enabled = NO;
        defineWeakSelf;
        [CoreSVP showSVPWithType:CoreSVPTypeLoadingInterface Msg:@"请稍后.." duration:.8f allowEdit:NO beginBlock:nil completeBlock:nil];
        [[WCNetworkAccessManager sharedMg] POST:[NSString stringWithFormat:self.urlCode, mobile] parameters:nil success:^(NSDictionary *data){
            [[WCPopupLayerManager shareMg] showTextOnly:data[@"data"] withView:self.view];
            
            //倒计时
            weakBtn.enabled = NO;
            [weakSelf countDown];
        } failure:nil netError:nil always:^{
            weakBtn.enabled = YES;
            [CoreSVP dismiss];
        }];
    } else {
        [[WCPopupLayerManager shareMg] showTextOnly:@"手机号错误" withView:self.view];
        return;
    }
}
#pragma mark - 注册

#pragma mark -注册
- (IBAction)goReg:(id)sender {
    NSString *account = self.account.text, *code = self.code.text, *password = self.password.text;
    
    if ([account isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请输入手机号" withView:self.view];
        return;
    }
    
    if ([code isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请输入验证码" withView:self.view];
        return;
    }
    
    if ([password isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请输入密码" withView:self.view];
        return;
    }
    
    if ([password hasSpace]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"密码不能有空格" withView:self.view];
        return;
    }
    
    if (![password isPassword]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"密码长度为6-16位" withView:self.view];
        return;
    }
  
    
    if ([account isMobile]) {
        __weak UIViewController *weakSelf = self;
        //关闭按钮
        __weak UIButton *weakBtn = sender;
        weakBtn.enabled = NO;
        
        NSMutableDictionary *parameters =[NSMutableDictionary dictionary];
        parameters[@"mobileNo"] =account;
        parameters[@"verifyCode"] =code;

        if (self.mode == WCViewControllerModeRegister) {
           
             parameters[@"password"] =[password md5String];
            
        }else{
             parameters[@"newPassword"] =[password md5String];
        
        }

        if (self.mode == WCViewControllerModeRegister){
             NSString *inviteStr =self.invateCodeTF.text;
            if (![inviteStr isEqualToString:@""] &&inviteStr) {
                parameters[@"salerCode"] =inviteStr;
            }
          
        }
//        if (self.mode == WCViewControllerModeRegister) {
//            NSString *inviteStr =self.invateCodeTF.text;
//            if (![inviteStr isEqualToString:@""] &&inviteStr) {
//                 parameters = @{@"mobileNo": account, @"verifyCode":code, @"password":[password md5String], @"salerCode":[]};
//                
//            }else{}
//           
//        } else {
//            parameters = @{@"mobileNo": account, @"verifyCode":code, @"newPassword":[password md5String]};
//        }
//        
        [CoreSVP showSVPWithType:CoreSVPTypeLoadingInterface Msg:@"请稍后.." duration:.8f allowEdit:NO beginBlock:nil completeBlock:nil];
        [[WCNetworkAccessManager sharedMg] POST:self.url
                                     parameters:parameters
                                        success:^(NSDictionary *data){
                                            CoreSVPSuccess(data[@"errMsg"]);
                                            
                                            [weakSelf performSelector:@selector(successPageback) withObject:nil afterDelay:1.0];
                                        } failure:nil netError:nil always:^{
                                            weakBtn.enabled = YES;
                                            [CoreSVP dismiss];
                                        }];
    } else {
        [[WCPopupLayerManager shareMg] showTextOnly:@"手机号错误" withView:self.view];
        return;
    }
}

- (IBAction)toggleShowPassword:(id)sender {
    UIButton *btn = sender;
    
    if (btn.selected) {
        [btn setSelected:NO];
        
        self.password.secureTextEntry = YES;
    } else {
        [btn setSelected:YES];
        
        NSString *passwordStr = self.password.text;
        self.password.text = @"";
        self.password.secureTextEntry = NO;
        self.password.text = passwordStr;
    }
}

- (IBAction)backgroundTap:(id)sender {
    [self.view endEditing:YES];
}


- (void)dealloc{
    [timerFgt deallocTimer];
    timerFgt =nil;

}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITextField *mustShow;
    if (self.account == textField) {
        mustShow = self.code;
    } else if(self.password == textField) {
        mustShow = self.password;
    }else if (self.invateCodeTF ==textField){
        mustShow =self.invateCodeTF;
    }
    
    CGRect rect = [mustShow convertRect:mustShow.bounds toView:self.view];
    CGFloat y = self.view.frame.size.height - rect.origin.y - rect.size.height - kKeyboardHeight;
    [self moveView:y];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    [self goReg:self.save];
    
    return YES;
}

#pragma mark - KeyBoard Note

- (void)keyboardWillHide:(NSNotification *)note
{
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options:7<<16
                     animations:^{
                         self.view.transform = CGAffineTransformIdentity;
                     } completion:NULL];
}

#pragma mark - Move View

- (void)moveView:(CGFloat)y
{
    #warning 为了配合键盘弹出的动画，使用7<<16.
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options:7<<16
                     animations:^{
                         self.view.transform = CGAffineTransformMakeTranslation(0, y>=0?0:y-10);
                     } completion:NULL];
}

@end
